package vip.manda.framework.auth;

import cn.hutool.db.Entity;
import cn.hutool.json.JSONUtil;
import vip.manda.framework.bean.Singleton;
import vip.manda.framework.data.DataType;
import vip.manda.framework.data.repository.impl.BaseRepositoryImpl;
import vip.manda.framework.util.Maps;
import vip.manda.framework.util.Timer;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author hongda.li 2022-04-14 13:33
 */
@Singleton
public class AuthRepository extends BaseRepositoryImpl {
    private final static String LOGIN_ID = "login_id";
    private final static String PERMISSIONS = "permissions";
    private final static String CREATE_TIME = "create_time";

    @Override
    public Map<String, DataType> getColumns() {
        Map<String, DataType> columns = new HashMap<>(Maps.size(3));
        columns.put("login_id", DataType.TEXT);
        columns.put("permissions", DataType.TEXT);
        columns.put("create_time", DataType.TEXT);
        return columns;
    }

    public boolean init(String loginId, String... permissions) {
        return insert(Entity.create()
                .set(LOGIN_ID, loginId)
                .set(PERMISSIONS, JSONUtil.toJsonStr(permissions))
                .set(CREATE_TIME, Timer.getSystemTime()));
    }

    public boolean add(String loginId, String... permissions) {
        List<String> list = get(loginId);
        for (String permission : permissions) {
            if (!list.contains(permission)) {
                list.add(permission);
            }
        }
        return update(Entity.create().set(PERMISSIONS, JSONUtil.toJsonStr(list)), Entity.create().set(LOGIN_ID, loginId));
    }

    public boolean del(String loginId, String... permissions) {
        List<String> list = get(loginId);
        for (String permission : permissions) {
            list.remove(permission);
        }
        return update(Entity.create().set(PERMISSIONS, JSONUtil.toJsonStr(list)), Entity.create().set(LOGIN_ID, loginId));
    }

    public boolean delAll(String loginId) {
        return delete(Entity.create().set(LOGIN_ID, loginId));
    }

    public List<String> get(String loginId) {
        Map<String, Object> one = findOne(Entity.create().set(LOGIN_ID, loginId));
        return JSONUtil.toList((String) one.get(PERMISSIONS), String.class);
    }
}
